<template>
  <div class="snake-container">
    <div class="game-area">
      <!-- 游戏主区域 -->
      <div class="game-board" ref="gameBoard" tabindex="0" @keydown="handleKeydown">
        <div v-for="(row, y) in gameMatrix" :key="y" class="board-row">
          <div v-for="(cell, x) in row" 
               :key="x" 
               :class="['board-cell', { 
                 'snake': isSnake(x, y),
                 'food': isFood(x, y),
                 'snake-head': isSnakeHead(x, y)
               }]">
          </div>
        </div>
      </div>

      <!-- 游戏信息面板 -->
      <div class="game-panel">
        <div class="game-stats">
          <div class="stat-item">
            <span class="stat-label">分数</span>
            <span class="stat-value">{{ score }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">最高分</span>
            <span class="stat-value">{{ highScore }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">速度</span>
            <span class="stat-value">{{ speed }}</span>
          </div>
        </div>

        <div class="game-controls">
          <button class="control-button" @click="startGame" :disabled="isPlaying">
            开始游戏
          </button>
          <button class="control-button" @click="pauseGame" :disabled="!isPlaying">
            {{ isPaused ? '继续' : '暂停' }}
          </button>
          <button class="control-button" @click="resetGame" :disabled="isPlaying && !isPaused">
            重新开始
          </button>
        </div>

        <div class="game-instructions">
          <h3>操作说明</h3>
          <ul>
            <li>← → ↑ ↓ : 控制方向</li>
            <li>空格 : 暂停/继续</li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

// 游戏配置
const BOARD_SIZE = 20
const INITIAL_SPEED = 200
const SPEED_INCREMENT = 10

// 游戏状态
const gameMatrix = ref(Array(BOARD_SIZE).fill().map(() => Array(BOARD_SIZE).fill(0)))
const snake = ref([])
const food = ref({ x: 0, y: 0 })
const direction = ref('right')
const nextDirection = ref('right')
const score = ref(0)
const highScore = ref(0)
const speed = ref(INITIAL_SPEED)
const isPlaying = ref(false)
const isPaused = ref(false)
const gameBoard = ref(null)
let gameLoop = null

// 初始化游戏
const initGame = () => {
  // 清空游戏板
  gameMatrix.value = Array(BOARD_SIZE).fill().map(() => Array(BOARD_SIZE).fill(0))
  
  // 初始化蛇的位置
  snake.value = [
    { x: 5, y: 5 },
    { x: 4, y: 5 },
    { x: 3, y: 5 }
  ]
  
  // 生成食物
  generateFood()
  
  // 重置其他状态
  direction.value = 'right'
  nextDirection.value = 'right'
  score.value = 0
  speed.value = INITIAL_SPEED
}

// 生成食物
const generateFood = () => {
  let x, y
  do {
    x = Math.floor(Math.random() * BOARD_SIZE)
    y = Math.floor(Math.random() * BOARD_SIZE)
  } while (snake.value.some(segment => segment.x === x && segment.y === y))
  
  food.value = { x, y }
}

// 检查位置是否是蛇身
const isSnake = (x, y) => {
  return snake.value.some(segment => segment.x === x && segment.y === y)
}

// 检查位置是否是食物
const isFood = (x, y) => {
  return food.value.x === x && food.value.y === y
}

// 检查位置是否是蛇头
const isSnakeHead = (x, y) => {
  return snake.value[0].x === x && snake.value[0].y === y
}

// 更新游戏状态
const updateGame = () => {
  if (!isPlaying.value || isPaused.value) return
  
  // 更新方向
  direction.value = nextDirection.value
  
  // 获取蛇头位置
  const head = { ...snake.value[0] }
  
  // 根据方向移动蛇头
  switch (direction.value) {
    case 'up': head.y--; break
    case 'down': head.y++; break
    case 'left': head.x--; break
    case 'right': head.x++; break
  }
  
  // 检查是否撞墙
  if (head.x < 0) head.x = BOARD_SIZE - 1
  if (head.x >= BOARD_SIZE) head.x = 0
  if (head.y < 0) head.y = BOARD_SIZE - 1
  if (head.y >= BOARD_SIZE) head.y = 0
  
  // 检查是否撞到自己
  if (snake.value.some(segment => segment.x === head.x && segment.y === head.y)) {
    endGame()
    return
  }
  
  // 移动蛇
  snake.value.unshift(head)
  
  // 检查是否吃到食物
  if (head.x === food.value.x && head.y === food.value.y) {
    score.value += 10
    if (score.value > highScore.value) {
      highScore.value = score.value
    }
    speed.value = Math.max(50, INITIAL_SPEED - Math.floor(score.value / 100) * SPEED_INCREMENT)
    generateFood()
  } else {
    snake.value.pop()
  }
}

// 键盘控制
const handleKeydown = (event) => {
  if (!isPlaying.value || isPaused.value) return
  
  switch (event.key) {
    case 'ArrowUp':
      if (direction.value !== 'down') nextDirection.value = 'up'
      break
    case 'ArrowDown':
      if (direction.value !== 'up') nextDirection.value = 'down'
      break
    case 'ArrowLeft':
      if (direction.value !== 'right') nextDirection.value = 'left'
      break
    case 'ArrowRight':
      if (direction.value !== 'left') nextDirection.value = 'right'
      break
    case ' ':
      event.preventDefault()
      pauseGame()
      break
  }
}

// 游戏控制
const startGame = () => {
  if (isPlaying.value) return
  
  initGame()
  isPlaying.value = true
  isPaused.value = false
  gameBoard.value?.focus()
  
  gameLoop = setInterval(updateGame, speed.value)
}

const pauseGame = () => {
  if (!isPlaying.value) return
  isPaused.value = !isPaused.value
}

const resetGame = () => {
  clearInterval(gameLoop)
  gameLoop = null
  isPlaying.value = false
  isPaused.value = false
  initGame()
}

const endGame = () => {
  isPlaying.value = false
  isPaused.value = false
  clearInterval(gameLoop)
  alert(`游戏结束！\n最终得分：${score.value}\n最高分：${highScore.value}`)
}

// 生命周期钩子
onMounted(() => {
  window.addEventListener('keydown', handleKeydown)
  initGame()
})

onUnmounted(() => {
  clearInterval(gameLoop)
  window.removeEventListener('keydown', handleKeydown)
})
</script>

<style scoped>
.snake-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  background-color: var(--theme-container-bg, #1a1a1a);
}

.game-area {
  display: flex;
  gap: 20px;
  padding: 20px;
  background-color: var(--theme-bg, #2d2d2d);
  border-radius: 12px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
}

.game-board {
  width: fit-content;
  height: fit-content;
  border: 2px solid var(--theme-border-color, #404040);
  background-color: var(--theme-container-bg, #1a1a1a);
  display: flex;
  flex-direction: column;
  outline: none;
  padding: 2px;
}

.board-row {
  display: flex;
}

.board-cell {
  flex: none;
  width: 20px;
  height: 20px;
  border: 1px solid var(--theme-border-color, #333);
  transition: all 0.1s;
}

.board-cell.snake {
  background-color: var(--theme-primary-color, #10b981);
}

.board-cell.snake-head {
  background-color: var(--theme-primary-color, #059669);
}

.board-cell.food {
  background-color: var(--theme-error-color, #ef4444);
  border-radius: 50%;
}

.game-panel {
  width: 200px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.game-stats {
  background-color: var(--theme-container-bg, #1a1a1a);
  padding: 15px;
  border-radius: 8px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: var(--theme-text-color, #e2e8f0);
}

.stat-label {
  font-size: 14px;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  color: var(--theme-primary-color, #60a5fa);
}

.game-controls {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.control-button {
  padding: 10px;
  border: none;
  border-radius: 6px;
  background-color: var(--theme-primary-color, #3b82f6);
  color: white;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.control-button:hover:not(:disabled) {
  background-color: var(--theme-primary-hover, #2563eb);
}

.control-button:disabled {
  background-color: var(--theme-secondary-color, #4b5563);
  cursor: not-allowed;
}

.game-instructions {
  background-color: var(--theme-container-bg, #1a1a1a);
  padding: 15px;
  border-radius: 8px;
  color: var(--theme-text-color, #e2e8f0);
}

.game-instructions h3 {
  margin: 0 0 10px;
  font-size: 16px;
}

.game-instructions ul {
  margin: 0;
  padding-left: 20px;
  font-size: 14px;
}

.game-instructions li {
  margin: 5px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .game-area {
    flex-direction: column;
    padding: 10px;
  }

  .game-board {
    margin: 0 auto;
  }

  .game-panel {
    width: 100%;
    max-width: 300px;
  }
}
</style> 